package server.session;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class Session {
    private SocketChannel channel;
    private Integer clientId ;
    private String clientName;

    private long lastActiveTime = System.currentTimeMillis();

    public void updateLastActive() {
        this.lastActiveTime = System.currentTimeMillis();
    }

    public long getLastActiveTime() {
        return lastActiveTime;
    }
    public Session(SocketChannel channel) {
        this.channel = channel;
        this.lastActiveTime = System.currentTimeMillis();
    }

    public void send(String msg) {
        try {
            byte[] bytes = (msg+"\n").getBytes(StandardCharsets.UTF_8);
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            channel.write(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (channel != null && channel.isOpen()) {

                channel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

